# coding: UTF-8
'''
Created on 2011-5-6

@author: yang_wanjun
'''
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.utils.translation import gettext_lazy as _
from senbzblog.comments.managers import CommentManager
from senbzblog.utils import constant

COMMENT_MAX_LENGTH = 255

class Comment(models.Model):
    
    # Basic
    user = models.ForeignKey(User, verbose_name=_('user'),
                    blank=True, null=True, related_name="%(class)s_comments")
    user_name = models.CharField(_("user's name"), max_length=50)
    user_email = models.EmailField(_("user's email address"))
    user_url = models.URLField(_("user's URL"), blank=True)
    comment = models.TextField(_('comment'), max_length=constant.COMMENT_MAX_LENGTH)

    # Metadata about the comment
    submit_date = models.DateTimeField(_('date/time submitted'), default=None)
    ip_address = models.IPAddressField(_('IP address'), blank=True, null=True)
    is_public = models.BooleanField(_('is public'), default=True,
                    help_text=_('Uncheck this box to make the comment effectively ' \
                                'disappear from the site.'))
    is_removed = models.BooleanField(_('is removed'), default=False,
                    help_text=_('Check this box if the comment is inappropriate. ' \
                                'A "This comment has been removed" message will ' \
                                'be displayed instead.'))
    
    # Content-object field
    content_type = models.ForeignKey(ContentType,
            verbose_name=_('content type'),
            related_name="content_type_set_for_%(class)s")
    object_pk = models.TextField(_('object ID'))
    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")

    # Metadata about the comment
    site = models.ForeignKey(Site)
    
    # Additional Attribute
    parent = models.ForeignKey('self', null=True, blank=True, default=0, related_name='children')
    is_mailnotify = models.BooleanField(default=False)
    pertain = models.IntegerField(null=True, blank=True)
    
    # Manager
    objects = CommentManager()
    
    class Meta:
        ordering = ['submit_date']
    
    def has_parent(self):
        return bool(self.parent_id)

    def get_parent(self):
        if self.parent_id:
            return Comment.objects.get(pk=self.parent_id)
        else:
            return None
        
    def has_children(self):
        return bool(self.children.get_children_by_id(self.id))
    
    def get_children(self):
        return self.children.get_children_by_id(self.id)
